import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式
import {getToken} from '@/utils/auth' // 从cookie中获取token
import getPageTitle from '@/utils/get-page-title'
import Vue from "vue";

NProgress.configure({showSpinner: false}) // 进度条配置

const whiteList = ['/login','/register'] // 不需要重定向名单


router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()

  if (hasToken && hasToken !== 'undefined') {

    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next({path: '/'})
      NProgress.done()
    } else {
      
      next()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // 没有访问权限的其他页将重定向到登录页。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

/**
 * 根据权限控制按钮的显示隐藏
 * ===========================================
 * */
// 是否有权限
const hasPermission = userPermission => {
  let userPermissionList = Array.isArray(userPermission) ? userPermission : [userPermission];
  // 当前用户的权限列表
  let permissionList = store.getters.roles
  return userPermissionList.some(e => permissionList.includes(e));
};
// 指令
Vue.directive('has', {
  inserted: (el, binding, vnode) => {
    if (!hasPermission(binding.value)) {
      // 将节点进行移除
      el.parentNode.removeChild(el);
    }
  }
});
// 全局判断方法
Vue.prototype.$_has = hasPermission;


router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
